using System.Text.Json;
using Mathmall.Administration.common;
using Mathmall.Administration.Mapper;
using Mathmall.Administration.Models;
using Mathmall.Administration.Vo;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

namespace Mathmall.Administration.Service.impl;

public class RoleService : IRoleService
{
    private readonly RoleMapper _roleMapper;
    private readonly RoleManager<IdentityRole<int>> _roleManager;

    public RoleService(RoleMapper roleMapper, RoleManager<IdentityRole<int>> roleManager)
    {
        _roleMapper = roleMapper;
        _roleManager = roleManager;
    }

    /// <summary>
    /// 添加角色
    /// </summary>
    /// <param name="roleName"></param>
    /// <returns></returns>
    public async Task<IdentityResult> AddRole(string roleName)
    {
        IdentityRole<int> role = new IdentityRole<int>() { Name = roleName };
        return await _roleMapper.AddRole(role);
    }

    /// <summary>
    /// 查询全部角色
    /// </summary>
    /// <returns></returns>
    public async Task<PaginatedList<IdentityRole<int>>> PageNationQuery(int pageIndex, int pageSize, string condition)
    {
        // 查询全部角色信息
        IQueryable<IdentityRole<int>> identityRoles =
            _roleMapper.QueryAllRoles().Where(role => role.Name.Contains(condition));

        // 计算角色总数
        int count = await identityRoles.CountAsync();
        // 进行分页
        List<IdentityRole<int>> roles =
            await identityRoles.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();

        return new PaginatedList<IdentityRole<int>>(roles, count, pageIndex, pageSize);
    }

    /// <summary>
    /// 查询全部角色
    /// </summary>
    /// <returns></returns>
    public async Task<List<IdentityRole<int>>> QueryAllRoles()
    {
        return await _roleManager.Roles.AsNoTracking().ToListAsync();
    }

    /// <summary>
    /// 更新角色名称
    /// </summary>
    /// <param name="role"></param>
    /// <returns></returns>
    public async Task<IdentityResult> UpdateRole(IdentityRole<int> role)
    {
        return await _roleManager.UpdateAsync(role);
    }

    /// <summary>
    /// 删除角色信息
    /// </summary>
    /// <param name="role"></param>
    /// <returns></returns>
    public async Task<IdentityResult> DeleteRole(IdentityRole<int> role)
    {
        return await _roleManager.DeleteAsync(role);
    }
}